package leetcodev1.字符串;

import leetcodev1.链表.Solution;

public class LeetCode91 {

    //想简单了
    public int numDecodings(String s) {
        int length = s.length(), ret = 0;
        for (int i = 0; i < length; i++) {
            if (s.charAt(i) == '0') {
                if (i == 0 || s.charAt(i - 1) > '2') {
                    return 0;
                }
                continue;
            }


            if (i + 1 < length) {
                int num = Integer.parseInt(s.substring(i, i + 2));
                if (num >= 1 && num <= 26 && num != 10 && num != 20) {
                    ret++;
                }
            }

        }

        return ret + 1;
    }
}

class Answer91 {

    //动态规划
    public int numDecodings(String s) {
        int n = s.length();
        int[] f = new int[n + 1];//第n位有多少种组合
        f[0] = 1;//默认1种
        for (int i = 1; i <= n; ++i) {
            if (s.charAt(i - 1) != '0') {
                //1个字符组合
                f[i] += f[i - 1];
            }
            if (i > 1 && s.charAt(i - 2) != '0' && ((s.charAt(i - 2) - '0') * 10 + (s.charAt(i - 1) - '0') <= 26)) {
                //两个字符组合
                f[i] += f[i - 2];
            }
        }
        return f[n];
    }

    //使用三个变量进行状态转换
    public int numDecodings1(String s) {
        int n = s.length();
        // a = f[i-2], b = f[i-1], c=f[i]
        int a = 0, b = 1, c = 0;
        for (int i = 1; i <= n; ++i) {
            c = 0;
            if (s.charAt(i - 1) != '0') {
                c += b;
            }
            if (i > 1 && s.charAt(i - 2) != '0' && ((s.charAt(i - 2) - '0') * 10 + (s.charAt(i - 1) - '0') <= 26)) {
                c += a;
            }
            a = b;
            b = c;
        }
        return c;
    }

}
